<template>
  <main-content class="vip-rank-rule" title="会员配置">
    <el-form :model="form" ref="formRef" :rules="formRules" :label-width="120">
      <content-divider title="基础配置"/>
      <el-form-item label="会员类型" prop="memberType" >
        <el-radio-group v-model="form.memberType" :disabled="!!form.memberType">
          <el-radio :label="1">内部会员</el-radio>
          <el-radio :label="2">外部会员</el-radio>
        </el-radio-group>
      </el-form-item>

      <template v-if="form.memberType === 1">
        <el-form-item label="有效期内保级" prop="keepGrade">
          <el-switch v-model:model-value="form.keepGrade" :active-value="1" :inactive-value="0"></el-switch>
        </el-form-item>

        <el-form-item v-if="form.keepGrade" label="有效期" prop="validityTime">
          <el-row :gutter="10">
            <el-col :span="14">
              <el-form-item prop="validityPeriod">
                <el-input v-model.number="form.validityPeriod" placeholder="请输入有效期" type="number"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item prop="validityType">
                <el-select v-model="form.validityType">
                  <el-option label="自然日" :value="1"></el-option>
                  <el-option label="自然月" :value="2"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="2">
              <div style="display: flex; align-items: center; justify-content: center; height: 100%">
                <el-tooltip
                    effect="dark"
                    content=""
                    placement="top"
                >
                  <template #content>
                    有效期 <br />
                    1、自然月:从会员升级日开始计算,<br />例如小明1月5日升级成LV2,有效期为6个自然月,则有效期到6月30日<br />
                    2、自然日:从会员升级日开始计算,<br />例如小明1月1日升级成LV2,有效期为90天(自然日),则有效期到3月31日<br />
                  </template>
                  <el-icon><InfoFilled /></el-icon>
                </el-tooltip>
              </div>
            </el-col>
          </el-row>
        </el-form-item>
      </template>

      <template v-if="form.memberType === 2">

        <el-form-item label="选择会员" prop="memberConfigId">
          <ScSelector
              v-model="form.memberConfigId"
              placeholder="请选择会员"
              type="config"
              :params="{ attach: 'member' }"
              :showFilterTags="false"
          >
          </ScSelector>
        </el-form-item>
      </template>

      <el-form-item label="支付配置" prop="payConfigId">
        <ScSelector
            v-model="form.payConfigId"
            placeholder="请选择支付配置"
            type="config"
            :params="{ attach: 'pay' }"
        >
          <template #expand-pop="{ data }">
            <div v-if="data" class="detail-container">
              <div class="detail-text">
                <h3>
                  {{ data.info.name }}
                </h3>
              </div>
              <div class="detail-text_line">
                配置类型：{{ data.info.externalTypeName }}
              </div>
              <div class="detail-text_line">
                所属平台：{{ data.info.externalPlatformTypeName }}
              </div>
              <div class="detail-text_line">
                配置标识：{{ data.info.unique }}
              </div>
              <div class="detail-text_line">
                描述：{{ data.info.remark || "暂无" }}
              </div>
            </div>
          </template>
        </ScSelector>
      </el-form-item>
      <!-- 通知配置start -->
      <content-divider title="通知配置"/>
        <NoticeConfig service-type="member" ref="noticeConfigRef" :memberId="form.id" />
      <!-- 通知配置end-->

      <content-divider title="等级规则"/>
      <el-form-item label="会员等级规则" prop="rule">
        <rich-editor :initial-value="initialDetail" @change="handleChange"></rich-editor>
      </el-form-item>
    </el-form>

    <template #fixed-bottom>
      <div class="fixed-button">
        <el-button @click="submit" type="primary" v-has="['10100301']">保存</el-button>
      </div>
    </template>
  </main-content>


</template>
<script lang="ts">
export default {
  name: 'RankRule'
}
</script>
<script lang="ts" setup>
import {FormRules} from "element-plus";
import {Ref, UnwrapNestedRefs, UnwrapRef} from "vue";
import {getMemberConfig, getVipRankDetail, memberConfigEdit, submitRankDetail} from "@/api/vipCenter";
import {IMemberConfigEditData} from "@/api/modules/vipCenter";
import {positiveInteger} from "@/utils/commonRegexp";
import {useExternalMember} from "@/views/vipCenter/compositions/useExternalMember";
import NoticeConfig from "@/components/noticeConfig/index.vue"

const {externalMemberList, getExternalMember} = useExternalMember()

const formRules:UnwrapRef<FormRules> = reactive({
  memberType: [{
    required: true,
    trigger: "change",
    message: "请选择会员类型"
  }],
  validityTime: [{
    required: true,
    validator(rule: any, value: any, callback: any) {
      if (!positiveInteger.test("" + form.value.validityPeriod ?? "")) {
        callback("请输入正整数")
        return
      }

      if (!form.value.validityType) {
        callback("请选择有效期")
        return
      }

      callback()
    },
  }],
  memberConfigId: [{
    required: true,
    trigger: "change",
    message: "请选择会员"
  }],
  keepGrade: [{
    required: true,
    message: "请选择是否启用有效期内保级",
    validator(rule: any, value: any, callback: any) {
      if (form.value.keepGrade === undefined) {
        callback("请选择有效期")
        return
      }

      callback()
    },
  }],
  payConfigId: [{
    required: true,
    message: "请选择支付配置",
    validator(rule:any, value: any, callback:any) {
      if (!form.value.payConfigId) {
        callback("请选择支付配置")
      }
      callback()
    }
  }],
  memberRule: [{
    required: true,
    trigger: 'blur',
    validator: (rule: any, value: any, callback: any) => {
      if (!form.value.memberRule) {
        callback('请填写会员等级规则')
        return
      }
      callback()
    }
  }]
})

const initForm: () => IMemberConfigEditData = () => {
  return {
    id: undefined,
    memberType: 1,
    validityType: 1,
    validityPeriod: undefined,
    keepGrade: 1,
    payConfigId: undefined,
    memberRule: '',
    memberConfigId: undefined,
  }
}

const form: Ref<IMemberConfigEditData> = ref(initForm())

const noticeConfigRef=ref()
const formRef = ref()
const initialDetail:Ref<string> = ref('')
const getDetail = async () => {
  const rs = await getMemberConfig()
  if (rs.code === 200) {
    Object.keys(rs?.payload ?? {}).forEach((key: string) => {
      if (rs.payload && rs.payload[key] !== undefined) {
        form.value[key] = rs.payload[key]
      }
    })
    if(rs.payload){
       //通知配置
      const noticeInfo={
        noticeType:rs.payload.noticeType,
        noticeUserIds:rs.payload.noticeUserIds,
        noticePhones:rs.payload.noticePhones,
        noticeWebhookUrls:rs.payload.noticeWebhookUrls
      }
      noticeConfigRef.value?.getFormData(noticeInfo)
    }
    initialDetail.value = rs.payload?.memberRule ?? ""
  }
}

const handleChange = ({innerHTML}: { innerHTML: string }) => {
  form.value.memberRule = innerHTML
}

const submit = () => {
  formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      const data={...form.value}
      //添加通知配置参数
      const noticeData= await noticeConfigRef.value.validForm()
      data.noticeType=noticeData.noticeType
      data.noticePhones=noticeData.noticePhones
      data.noticeWebhookUrls=noticeData.noticeWebhookUrls
      data.noticeUserIds=noticeData.noticeUserIds?String(noticeData.noticeUserIds):undefined
      const rs = await memberConfigEdit(data)
      if (rs.code === 200) {
        ElMessage.success('保存成功')
      }
    } else {
      ElMessage.error("校验失败，请检查")
    }
  })
}

const store = useStore();
// 监听机构
const insId = computed(() => {
  return store.state.insId.insId;
});
watch(
    () => insId,
    () => {
      getDetail()
    },
    {
      deep: true
    }
)

onMounted(() => {
  getDetail();
  getExternalMember();
})

</script>

<style scoped lang="scss">
.fixed-button {
  padding: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
